<template>
  <!--评论模块-->
  <div class="reply-input-box" >
    <el-input
        v-model="state.commentDto.content"
        :autosize="{ minRows: 2 }"
        type="textarea"
        placeholder="这里需要一条查重率0%的评论!"
        @focusin="checkIsLogin"
    />
    <p><el-button type="primary" style="float: right;margin-top: 5px" @click="publishComment(true,-1,null)" >提交</el-button></p>
  </div>
  <h3 style="margin-bottom: 20px">共有{{state.total}}条评论</h3>
  <div class="comment-item-box" v-for="comment in state.commentList" :key="comment.id">
    <div class="left">
      <el-avatar :size="48"
                 :src="comment.user.avatar"/>
    </div>
    <div class="right">
      <div class="root-comment">
        <span class="nickName">{{comment.user.nickName}}</span>
        <p class="comment-content">
          {{ comment.content }}
        </p>
        <p class="comment-bottom">
          <span class="time">{{comment.createTime}}</span>

          <span class="reply" @click="openReplyBox(comment)">回复</span>
        </p>
        <div class="reply-input-box" v-show="state.currentReplyCommentSetting.commentId===comment.id">
          <el-input
              v-model="state.commentDto.content"
              :autosize="{ minRows: 2 }"
              type="textarea"
              :placeholder="state.currentReplyCommentSetting.placeholder"
          />
          <p><el-button type="primary" style="float: right;margin-top: 5px" @click="publishComment(false,comment.id,null)">提交</el-button></p>
        </div>
      </div>
      <div class="reply-box">


        <div class="reply-item" v-if="comment.children&& comment.children.data.length>0" v-for="reply in comment.children.data" :key="reply.id">
          <el-avatar :size="30"
                     :src="reply.user.avatar"/>
          <div class="reply-item-right">
            <div class="reply-item-header">
              <span class="nickName">{{ reply.user.nickName }}</span>
              <span class="reply-flag" v-if="reply.replyToUser">回复&nbsp</span>
              <span class="reply-target" v-if="reply.replyToUser">@{{reply.replyToUser.nickName}}&nbsp;:</span>
              <span class="reply-comment-content" style="margin-left: 5px">
              {{reply.content}}
             </span>
            </div>
            <p class="comment-bottom">
              <span class="time">{{reply.createTime}}</span>

              <span class="reply"  @click="openReplyBox(reply)">回复</span>
            </p>
            <div class="reply-input-box" v-show="state.currentReplyCommentSetting.commentId===reply.id">
              <el-input
                  v-model="state.commentDto.content"
                  :autosize="{ minRows: 2 }"
                  type="textarea"
                  :placeholder="state.currentReplyCommentSetting.placeholder"
              />
              <p><el-button type="primary" style="float: right;margin-top: 5px" @click="publishComment(false,reply.parentId,reply.user.userId)">提交</el-button></p>
            </div>
          </div>

        </div>
        <el-pagination v-if="comment.children&& comment.children.data.length>0"
                       hide-on-single-page
                       @currentChange="(value)=>replyPageChange(value,comment.id,comment.children.data)"
                       small layout="prev, pager, next" :page-size="10" :total="comment.children.total"
                       style="--el-pagination-bg-color: transparent;
                       font-weight: 600;
                       --el-pagination-button-disabled-bg-color:transparent"/>
      </div>

    </div>

  </div>
  <div class="load" ref="loadingRef">
    <div class="load-item"  v-loading="state.loading"></div>
  </div>
</template>

<script setup>

import {onBeforeUnmount, onMounted, reactive, ref, watch} from "vue";
import CommentApi from "@/api/CommentApi.js";
import {useRoute} from "vue-router";
import {ElMessage} from "element-plus";
const route = useRoute()
import {useLoginStore} from "@/store/index.js";
const {userIsLogin,openLoginDialog,getUserLoginInfo} = useLoginStore()
const props = defineProps({
  videoCode: {
    type: String
  }
})
const state = reactive({
  commentDto:{
    content:null,
    parentId:null,
    videoCode:route.params.videoCode,
    replyId:null,
    userId:getUserLoginInfo().userId,
    replyUserId:null
  },
  queryDto: {
    pageNum: 1,
    size: 10,
    videoCode: null
  },
  loading:false,
  commentList: [],
  total:0,
  observer:null,
  currentReplyCommentSetting:{
    commentId:null,
    replyUserName:null,
    placeholder:"这里需要一条查重率0%的评论!"
  }
})
const loadingRef = ref()
const initDto=()=>{
  state.commentDto.content=null
  state.commentDto.parentId=null
  state.commentDto.replyUserId=null
  state.commentDto.replyId=null
  state.currentReplyCommentSetting.commentId=null
  state.currentReplyCommentSetting.replyUserName=null
}
const getCommentList = (isAppend,videoCode,isInitPageNum)=>{
  state.queryDto.videoCode = videoCode
  if (isInitPageNum){
    state.queryDto.pageNum=1
  }
  CommentApi.getVideoComment(state.queryDto).then(res => {
    state.loading = false
    if (isAppend){
      if (res.data&& res.data.length>0){
        res.data.forEach(c=>{
          state.commentList.push(c)
        })
      }


    }else {
      state.commentList= res.data.data
      state.total = res.data.total
    }


  })
}
const replyPageChange = (value,parentId)=>{
  CommentApi.getReplyComment({pageNum: value,size:1,videoCode:state.queryDto.videoCode,parentId:parentId}).then(res=>{
    state.commentList.find(comment => comment.id ===parentId ).children.data=res.data.data

  })
}
onMounted(()=>{
  state.queryDto.videoCode = route.params.videoCode
  getCommentList(false,route.params.videoCode)
  // 构建观察器
  state.observer = new IntersectionObserver(
      ([{ isIntersecting }]) => {
        // 目标元素与根元素相交
        if (isIntersecting) {
          state.loading = true
          state.queryDto.pageNum = state.queryDto.pageNum+1
          getCommentList(true,state.queryDto.videoCode)
        }
      },
      {
        threshold: 1 // 相交距离
      }
  )
  // 观察目标元素
  state.observer.observe(loadingRef.value)

})

onBeforeUnmount(() => {
  state.observer.disconnect()
})
const checkIsLogin = ()=>{
  if (!userIsLogin()){
    ElMessage.error("请先登录!")
    openLoginDialog()
    return
  }
}
const openReplyBox = (comment)=>{
  //校验用户是否登录
  if (!userIsLogin()){
    ElMessage.error("请先登录!")
    openLoginDialog()
    return
  }
  state.commentDto.replyId =comment.id
  state.currentReplyCommentSetting.commentId = comment.id
  state.currentReplyCommentSetting.placeholder=`回复: @${comment.user.nickName}`
}
const publishComment = (isRoot,parentId,replyUserId)=>{
  if (!userIsLogin()){
    ElMessage.error("请先登录!")
    return
  }
  if (state.commentDto.content===null || state.commentDto.content===""){
    ElMessage.error("请输入评论内容!")
    return
  }
  state.commentDto.parentId = parentId
  state.commentDto.replyUserId = replyUserId

  CommentApi.publishComment(state.commentDto).then(res=>{
    if (!res.flag){
      ElMessage.error(res.message)
      return
    }
    initDto()
    state.queryDto.pageNum = 1
    getCommentList(false,state.queryDto.videoCode)
  })
}
defineExpose({
  getCommentList
})
</script>
<style scoped lang="less">
.comment-item-box {
  display: flex;
  align-items: flex-start;
  margin-bottom: 30px;

  .left {

  }

  .right {
    flex:1;
    margin-left: 15px;

  }

  //根评论样式
  .root-comment {
    display: flex;
    flex-direction: column;

    .nickName {
      margin-bottom: 10px;
      letter-spacing: 1px;
      font-weight: 600;
      font-size: 15px;
    }

    .comment-content {
      font-size: 15px;
      letter-spacing: 1px;
      line-height: 2px;
      margin: 10px 0 10px 0;
    }

  }
}

.reply-box {
  //background-color: #f4f4f4;
  padding: 10px;
  border-radius: 8px;
  margin-top: 8px;
}

.reply-item {
  display: flex;
  margin-bottom: 10px;

  .reply-item-right {

    flex: 1;
    margin-left: 10px;

    .reply-item-header {
      .nickName {
        letter-spacing: 1px;
        font-size: 14px;
        font-weight: 600;
      }

      .reply-flag {
        margin-left: 10px;
      }

      .reply-target {
        font-size: 15px;
        color: #00aadf;
        font-weight: 500;
      }

      .reply-comment-content {
        font-size: 15px;
        letter-spacing: 2px;
        line-height: 150%;
      }
    }
  }
}

.comment-bottom {
  display: flex;
  flex-direction: row;
  font-size: 13px;
  margin-top: 8px;

  .like {
    margin: 0 15px;
  }
  .reply {
    margin-left: 5px;
    cursor: pointer;
  }
  .reply:hover{
    color: #409eff;
  }
}
.load{
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  .load-item{
    width: 60px;
    height: 60px;
  }
}
:deep(.el-loading-mask){
  background-color: transparent;
}
.reply-input-box{
  width: 100%;
  padding: 1px;
  margin: 10px 0;
}
</style>